package com.zmzncs.lmtc.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.zmzncs.lmtc.common.pojo.ChnnelsBody;
import com.zmzncs.lmtc.common.pojo.ResultHead;
import com.zmzncs.lmtc.common.pojo.daoer.*;
import com.zmzncs.lmtc.module.park.dao.ParkInfoDao;
import com.zmzncs.lmtc.module.park.pojo.park_info_daoer.ParkInfoDaoer;
import com.zmzncs.lmtc.module.park.pojo.parkinfo.ParkInfoDTO;
import com.zmzncs.lmtc.module.park.service.ParkInfoDaoerService;
import com.zmzncs.lmtc.module.park.service.ParkInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 道尔
 */
@Slf4j
@Component
public class DaoerApiUtil {

    public final static Integer SUCCESS_STATUS = 1;
    //测试环境
//    final static String REFERER = "https://cloud-beta.drzk.cn";
    //PRO环境
    final static String REFERER = "https://cloud-2018.drzk.cn";

    final static String TOKEN_URL = "/api/index/auth/token";
    final static String GET_CAR_FEE = "/api/index/tempFee/getcarfee";
    final static String ONANDOFF =  "/api/index/onandoff";
    final static String GET_CHANNELS =  "/api/index/getchannels";
//    final static String GET_CARFEE =  "/apiDocumentation?url=tempCar&name=0";
    final static String GET_CARFEE =  "/api/index/tempFee/getcarfee";
    final static String GET_PARKING =  "/api/getparking";
    final static String GET_MONTH_AMOUNT =  "/api/index/monthlycar/long-rental-rate";
    final static String GET_MONTH_CAR =  "/api/index/monthlycar/info";  //  月租车基本信息
    final static String GET_CAR_PORT =  "/api/index/carport";  //  查询车位
    final static String GET_CAR_INS =  "/api/index/carins";  //  查询进场记录
    final static String GET_CAR_OUTS =  "/api/index/carouts";  //  查询出场记录
    final static String CREATE_MONTH =  "/api/index/monthlycar/create"; //  购买月卡
    final static String MONTH_RENEWAL =  "/api/index/monthlycar/newdate";   //  月卡续时
    final static String MONTH_DEL =  "/api/index/monthlycar/del";   //  月租车销户
    final static String LOCK_CAR =  "/api/index/lockCar/lockCar";   //  月租车锁车/解锁


    @Autowired
    ParkInfoDao parkInfoDao;

    private static DaoerApiUtil daoerApiUtil;
    @PostConstruct
    public void init() {
        daoerApiUtil = this;
    }


    /**
     * 查询进场记录
     */
    public static CarInsOutsRes getCarIns(String parkId, String carNo, String startTime, String endTime, Integer pageNum, Integer pageSize){
        long startLogTime = new Date().getTime();

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token", token);
        headers.put("Referer", REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);   //  第三方应用车场编号
        params.put("carNo", carNo);   //  根据车牌查询入场记录
        params.put("startTime", startTime);   //  开始时间 yyyy-MM-dd HH:mm:ss
        params.put("endTime", endTime);   //  结束时间 yyyy-MM-dd HH:mm:ss
        params.put("pageNum", pageNum);   //  页码，查的es，默认从0开始，或者不传也可以
        params.put("pageSize", pageSize);   //  每页显示多少条数据
        String jsonParams =  JSON.toJSONString(params);
        log.info("道尔进场记录请求参数：" + jsonParams);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+GET_CAR_INS, jsonParams, headers);
        log.info("道尔进场记录响应数据：{}，耗时{}ms", resultStr, new Date().getTime()-startLogTime);

        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        try {
            Integer status = resultHead.getHead().getStatus();
            if(SUCCESS_STATUS.equals(status)){
                return JsonUtil.JSONToObj(resultStr, CarInsOutsRes.class);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        CarInsOutsRes carInsOutsRes = new CarInsOutsRes();
        CarInsOutsRes.Head head = new CarInsOutsRes.Head();
        head.setStatus(resultHead.getHead().getStatus());
        head.setMessage(resultHead.getHead().getMessage());
        carInsOutsRes.setHead(head);

        return carInsOutsRes;
    }

    /**
     * 查询出场记录
     */
    public static CarInsOutsRes getCarOuts(String parkId, String carNo, String startTime, String endTime, Integer pageNum, Integer pageSize){
        long startLogTime = new Date().getTime();

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer", REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);   //  第三方应用车场编号
        params.put("carNo", carNo);   //  根据车牌查询入场记录
        params.put("startTime", startTime);   //  开始时间 yyyy-MM-dd HH:mm:ss
        params.put("endTime", endTime);   //  结束时间 yyyy-MM-dd HH:mm:ss
        params.put("pageNum", pageNum);   //  页码，页码，查的es，默认从0开始，或者不传也可以
        params.put("pageSize", pageSize);   //  每页显示多少条数据
        String jsonParams =  JSON.toJSONString(params);
        log.info("道尔出场记录请求参数：" + jsonParams);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+GET_CAR_OUTS, jsonParams, headers);
        log.info("道尔出场记录响应数据：{}，耗时{}ms", resultStr, new Date().getTime()-startLogTime);

        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        try {
            Integer status = resultHead.getHead().getStatus();
            if(SUCCESS_STATUS.equals(status)){
                return JsonUtil.JSONToObj(resultStr, CarInsOutsRes.class);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        CarInsOutsRes carInsOutsRes = new CarInsOutsRes();
        CarInsOutsRes.Head head = new CarInsOutsRes.Head();
        head.setStatus(0);
        head.setMessage(resultHead.getHead().getMessage());
        carInsOutsRes.setHead(head);

        return carInsOutsRes;
    }

    /**
     * 查询车位
     */
    public static CarPortRes getCarPort(String parkId){
        long startTime = new Date().getTime();

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer", REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        String jsonParams =  JSON.toJSONString(params);
        log.info("道尔查询车位请求参数：" + jsonParams);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+GET_CAR_PORT, jsonParams, headers);
        log.info("道尔查询车位响应数据：{}，耗时{}ms", resultStr, new Date().getTime()-startTime);

        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        try {
            Integer status = resultHead.getHead().getStatus();
            if(SUCCESS_STATUS.equals(status)){
                return JsonUtil.JSONToObj(resultStr, CarPortRes.class);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        CarPortRes carPortRes = new CarPortRes();
        CarPortRes.Head head = new CarPortRes.Head();
        head.setStatus(0);
        head.setMessage(resultHead.getHead().getMessage());
        carPortRes.setHead(head);

        return carPortRes;
    }

    /**
     * 获取车场通道
     */
    public static ChnnelsBody getGetChannels(String parkId) {

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
                return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        String jsonParams =  JSON.toJSONString(params);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+GET_CHANNELS, jsonParams, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        Integer status = resultHead.getHead().getStatus();
        if(SUCCESS_STATUS.equals(status)){
            ChnnelsBody chnnels = JsonUtil.JSONToObj(resultStr, ChnnelsBody.class);
            return chnnels;
        }
        return null;
    }

    /**
     * 获取临时车缴纳金额
     * @param parkId    第三方应用车场编号
     * @param carNo 车牌号码
     */
    public static CarFeeRes getcarfee(String parkId, String carNo) {
        long startTime = new Date().getTime();

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("carNo", carNo);//车牌号码
        String jsonParams =  JSON.toJSONString(params);
        log.info("道尔实时订单金额请求参数：" + jsonParams);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+GET_CARFEE, jsonParams, headers);
        log.info("道尔实时订单金额响应数据：{}，耗时{}ms", resultStr, new Date().getTime()-startTime);

        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        try {
            Integer status = resultHead.getHead().getStatus();
            if(SUCCESS_STATUS.equals(status)){
                CarFeeRes carFeeRes = JsonUtil.JSONToObj(resultStr, CarFeeRes.class);
                return carFeeRes;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        CarFeeRes carFeeRes = new CarFeeRes();
        CarFeeRes.Head head = new CarFeeRes.Head();
        head.setStatus(0);
        head.setMessage(resultHead.getHead().getMessage());
        carFeeRes.setHead(head);

        return carFeeRes;
    }

    /**
     * 获取停车场信息
     * @param parkId    第三方应用车场编号
     */
    public static ParkingInfo getParking(String parkId) {

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        String resultStr = HttpUtil.getIntance().get(REFERER+GET_PARKING+"/"+parkId,
                null, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        Integer status = resultHead.getHead().getStatus();
        if(SUCCESS_STATUS.equals(status)){
            ParkingInfo parkingInfo = JsonUtil.JSONToObj(resultStr, ParkingInfo.class);
            return parkingInfo;
        }
        return null;
    }

    /**
     * 获取月租费率
     * @param parkId    第三方应用车场编号
     */
    public static MonthAmount getMonthAmount(String parkId) {
        log.info("获取停车场信息：【{}】", parkId);
        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        String resultStr = HttpUtil.getIntance().get(REFERER+GET_MONTH_AMOUNT+"/"+parkId, null, headers);
        log.info("请求响应结果：" + resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        Integer status = resultHead.getHead().getStatus();

        if(SUCCESS_STATUS.equals(status)){
            MonthAmount monthAmount = JsonUtil.JSONToObj(resultStr, MonthAmount.class);
            return monthAmount;
        }
        return null;
    }

    /**
     * 月租车基本信息
     * @param parkId    第三方应用车场编号
     * @param carNo 车牌号码
     */
    public static MonthlyCarInfoRes getMonthlycar(String parkId, String carNo) {
        MonthlyCarInfoRes monthlyCarInfoRes = new MonthlyCarInfoRes();

        long startTime = new Date().getTime();

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            return monthlyCarInfoRes;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("carNo", carNo);//车牌号码
        String jsonParams =  JSON.toJSONString(params);
        log.info("道尔车牌月租信息请求参数：" + jsonParams);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+GET_MONTH_CAR, jsonParams, headers);
        log.info("道尔车牌月租信息响应数据：{}，耗时{}ms", resultStr, new Date().getTime()-startTime);

        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);
        try {
            Integer status = resultHead.getHead().getStatus();
            if(SUCCESS_STATUS.equals(status)){
                monthlyCarInfoRes = JsonUtil.JSONToObj(resultStr, MonthlyCarInfoRes.class);
                return monthlyCarInfoRes;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        MonthlyCarInfoRes.Head head = new MonthlyCarInfoRes.Head();
        head.setStatus(0);
        head.setMessage(resultHead.getHead().getMessage());
        monthlyCarInfoRes.setHead(head);

        return monthlyCarInfoRes;
    }

    /**
     * 购买月卡  开户
     */
    public static Map<String, Object> buyMonthCard(String parkId, String carNo, Integer cardTypeId, Date startTime, Date endTime, BigDecimal balanceMoney, String contactName, String concatPhone) {
        Map<String, Object> map = new HashMap<>();

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            map.put("status","0");
            map.put("message","Token为空");
            return map;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("carNo", carNo);//车牌号码
        params.put("cardTypeId", cardTypeId);//卡类型编号：11~18:月租车A~H,41~42:免费车A~B,51~58:储值车A~H
        params.put("startTime", DateTimeUtil.convertYMDHMS(startTime));//月租开始时间 yyyy-MM-dd HH:mm:ss
        params.put("endTime", DateTimeUtil.convertYMDHMS(endTime));//月租结束时间 yyyy-MM-dd HH:mm:ss
        params.put("balanceMoney", balanceMoney);   //收费金额
        params.put("payType", 1); //0 现金 1微信 2支付宝
        params.put("contactName", contactName);//人员名称
        params.put("concatPhone", concatPhone);//人员手机号码

        String jsonParams =  JSON.toJSONString(params);
        log.info("道尔购买月卡请求参数：{}", jsonParams);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+CREATE_MONTH, jsonParams, headers);
        log.info("道尔购买月卡响应数据：{}", resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);

        Integer status = resultHead.getHead().getStatus();
        String message = resultHead.getHead().getMessage();

        map.put("status", status);
        map.put("message", message);
        return map;
    }

    /**
     * 月卡续期
     */
    public static Map<String, Object> monthRenewal(String parkId, String carNo, Date startTime, Date endTime, BigDecimal balanceMoney) {
        Map<String, Object> map = new HashMap<>();

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            map.put("status", 0);
            map.put("message", "Token为空");
            return map;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer",REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("carNo", carNo);//车牌号码
        params.put("newStartTime", DateTimeUtil.convertYMDHMS(startTime));//月租开始时间 yyyy-MM-dd HH:mm:ss
        params.put("newEndTime", DateTimeUtil.convertYMDHMS(endTime));//月租结束时间 yyyy-MM-dd HH:mm:ss
        params.put("balanceMoney", balanceMoney);//收费金额
        params.put("payType", 1);//0 现金 1微信 2支付宝

        String jsonParams =  JSON.toJSONString(params);
        log.info("道尔续租月卡请求参数：{}", jsonParams);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+MONTH_RENEWAL, jsonParams, headers);
        log.info("道尔续租月卡响应数据：{}", resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);

        Integer status = resultHead.getHead().getStatus();
        String message = resultHead.getHead().getMessage();

        map.put("status", status);
        map.put("message",message);
        return map;
    }

    /**
     * 月租车销户
     */
    public static Map<String, Object> monthDel(String parkId, String carNo) {
        Map<String, Object> map = new HashMap<>();

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            map.put("status", 0);
            map.put("message", "Token为空");
            return map;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer", REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("carNo", carNo);//车牌号码

        String jsonParams =  JSON.toJSONString(params);
        log.info("道尔月租车销户请求参数：{}", jsonParams);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+MONTH_DEL, jsonParams, headers);
        log.info("道尔月租车销户响应数据：{}", resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);

        Integer status = resultHead.getHead().getStatus();
        String message = resultHead.getHead().getMessage();

        map.put("status", status);
        map.put("message",message);
        return map;
    }

    /**
     * 月租车锁车/解锁
     */
    public static Map<String, Object> lockUnlockCar(String parkId, String carNo, Integer carStatus) {
        Map<String, Object> map = new HashMap<>();

        String token = getToken(parkId);
        if(StringUtils.isBlank(token)){
            map.put("status", 0);
            map.put("message", "Token为空");
            return map;
        }
        Map<String, String> headers = Maps.newHashMap();
        headers.put("token",token);
        headers.put("Referer", REFERER);

        Map<String, Object> params = Maps.newHashMap();
        params.put("parkId", parkId);//停车场ID
        params.put("carNo", carNo);//车牌号码
        params.put("status", carStatus);    //  默认为1, 1锁定，0解锁

        String jsonParams =  JSON.toJSONString(params);
        log.info("道尔月租车锁车/解锁请求参数：{}", jsonParams);
        String resultStr = HttpUtil.getIntance().postJson(REFERER+LOCK_CAR, jsonParams, headers);
        log.info("道尔月租车锁车/解锁响应数据：{}", resultStr);
        ResultHead resultHead = JsonUtil.JSONToObj(resultStr, ResultHead.class);

        Integer status = resultHead.getHead().getStatus();
        String message = resultHead.getHead().getMessage();

        map.put("status", status);
        map.put("message",message);
        return map;
    }

    /**
     * 获取token
     */
    public static synchronized  String getToken(String parkId) {
        MapCacheManager.deleteTimeOut();
        String token = (String)MapCacheManager.getCache("token");
        if(StringUtils.isBlank(token)){
            ParkInfoDTO parkInfoDTO = daoerApiUtil.parkInfoDao.getByBolianParkId(parkId);
            if (parkInfoDTO == null || StringUtils.isBlank(parkInfoDTO.getDaoerSecretKey())){
                log.error("获取道尔AppName空");
            }

            Map<String, Object> paramsa = Maps.newHashMap();
            paramsa.put("appName", parkInfoDTO.getDaoerSecretKey());
            paramsa.put("parkId", parkId );//停车场ID
            String jsonParams =  JSON.toJSONString(paramsa);
            String response =  HttpUtil.getIntance().postJson(REFERER+TOKEN_URL, jsonParams);
            Integer status = Integer.parseInt(JSONObject.parseObject(response).get("status").toString());
            if(SUCCESS_STATUS.equals(status)){
                token = JSONObject.parseObject(response).get("data").toString();
                MapCacheManager.setCache("token",token,7200*1000);
                return token;
            }
            log.error("获取道尔token错误：" + response);
        }
        return token;
    }

}
